<template>
    <el-dialog :model-value="dialogVisible" title="城市选择" width="800px" :before-close="handleClose" append-to-body>
        <el-form ref="formRef" :model="dataForm" label-width="10px" :rules="rules" :inline="false">
            <el-form-item prop="subjectName" style="padding:10px;margin-bottom:10px" label="已选：" label-width="57px">
                <el-tag v-for="(item, index) in selectCheckList" :key="index" class="tags" closable
                    :type="item.areaName" @close="removeTab(index, item)">
                    {{ item.areaName }}
                </el-tag>
            </el-form-item>
            <el-form-item>
                <div class="head">
                    <el-tabs v-model="tabsValue" class="demo-tabs" style="margin-bottom:25px;width:100%"
                        @tab-click="tabClick()">
                        <el-tab-pane v-for="item in tabsList" :key="item.org" :label="item.label" :name="item.value">
                        </el-tab-pane>
                    </el-tabs>
                </div>
                <el-row style="width:100%;border:1px solid #dcdfe6;border-radius:5px;"
                    v-show="['inner', 'out'].includes(tabsValue)">
                    <el-col :span="12">
                        <div class="head"></div>
                        <div class="city-box">
                            <div class="search-input">
                                <el-input placeholder="输入城市名称搜索" v-model="filterText" clearable></el-input>
                            </div>
                            <el-tree class="filter-tree" :data="tabsValue == 'inner' ? dataSourceIn : dataSourceOut"
                                :props="defaultProps" default-expand-all :filter-node-method="filterNode" ref="treeRef"
                                node-key="id" @check="currentChange" show-checkbox>

                            </el-tree>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="head">
                            <p>已选 {{ selectNum }}/{{ cityDataList.length }}</p>
                            <p @click="allCheck">全选</p>
                        </div>
                        <div class="selec-city">
                            <div class="subject-con">
                                <div v-for="(item, index) in cityDataList" :key="index" class="subject-list">
                                    <p>{{ item.areaName }}</p>
                                    <div class="check-box" @click="selectCity(index)">
                                        <img :src="selectIcon" alt v-if="item.isSelect" />
                                        <img :src="noSelectIcon" alt v-else />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <div style="width:100%" v-show="tabsValue == 'type'">
                    <div class="subject-con">
                        <div v-for="(item, index) in cityTypeList" :key="index" class="subject-list">
                            <p>{{ item.categoryName }}</p>
                            <div class="check-box" @click="selectSCityType(index)">
                                <img :src="selectIcon" alt v-if="item.isSelect" />
                                <img :src="noSelectIcon" alt v-else />
                            </div>
                        </div>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import selectIcon from '@/assets/images/check_select.png'
import noSelectIcon from '@/assets/images/check_no_select.png'
import { onMounted, watch } from "vue";
import { treeData } from '@/util/index'
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    targetArea: {
        type: String,
        default: ''
    }


})

const dataForm = ref({
    subjectName: ''
})


const cityDataList = ref([])

const defaultProps = ref({
    label: 'areaName',
    children: 'children',

})
const subjectOldDataList = ref([...cityDataList.value])

const formRef = ref(null)

const selectCheckList = ref([])

const emit = defineEmits(['on-update', 'handleClose'])


const selectNum = computed(() => {
    let list = []
    cityDataList.value.forEach((item) => {
        if (item.isSelect) list.push(item)
    })
    // selectCheckList.value = list
    return list.length
})


const tabsList = ref([
    { label: '国内', value: 'inner' },
    { label: '国外', value: 'out' },
    { label: '类型', value: 'type' }
])

const tabsValue = ref('inner')

const filterText = ref('')

const treeRef = ref('')

const cityTypeList = ref([])

const treeListOut = ref([]) // 国外已选择的城市

const treeListIn = ref([]) // 国内已选择的城市


const dataSourceOut = ref([])

const dataSourceIn = ref([])

watch(() => (filterText.value), (newVal, oldVal) => {
    treeRef.value.filter(newVal)
})

onMounted(() => {

    getCityTypeList()
    getCityList(true) // 国外
    getCityList(false) // 国内

    if (props.targetArea != '') {
        // 编辑
        try {
            let obj = typeof props.targetArea == 'string' ? JSON.parse(props.targetArea) : props.targetArea
            setTimeout(() => {
                cityTypeEcho(obj.cityTypes)
                selectCheckList.value = obj.selectCheckList

                treeListIn.value = obj.treeListIn
                treeListOut.value = obj.treeListOut
                if (tabsValue.value == 'inner') cityDataList.value = treeListIn.value
                if (tabsValue.value == 'out') cityDataList.value = treeListOut.value

                let list = []
                obj.treeListIn.forEach(item => {
                    if (item.isSelect) list.push(item.id)
                })
                treeRef.value.setCheckedKeys(list)
                cityDataList.value = obj.treeListIn
            }, 800)

        } catch (error) {

        }
    } else {
        cityTypeList.value.forEach(item => {
            item['isSelect'] = false
        })
    }
})
//城市类型回显
const cityTypeEcho = (list) => {
    let ids = []
    list.forEach(item => ids.push(item.id))

    selectEcho(ids, cityTypeList.value)

}
// 获取选中的数据
const selectEcho = (ids, list) => {
    let selectArr = []
    ids.forEach(item => {
        list.forEach(item2 => {
            if (item == item2.id) {
                item2['isSelect'] = true
                selectArr.push(item2)

            }
        })
    })
    selectCheckList.value = [...selectCheckList.value, ...selectArr]
    return list
}
// 城市搜索
const filterNode = (value, data) => {

    if (!value) return true
    return data.areaName.includes(value)
}


// 获取城市类型列表数据
const getCityTypeList = () => {
    const parms = {
        pageNum: 1,
        pageSize: 100
    }
    api.feeConfig.cityTypeList(parms).then(res => {
        const { list, total } = res
        list.forEach(item => {
            item['isSelect'] = false
            item['oversea'] = 'type'
        })
        cityTypeList.value = list

    })

}
// 获取国内、国外城市 列表数据
const getCityList = (oversea) => {
    api.dataMaintenance.cityMangerList({ oversea }).then(res => {
        let result = treeData(res, 'areaCode', 'parentAreaCode')
        oversea == true ? dataSourceOut.value = result : dataSourceIn.value = result
    })
}

const tabClick = () => {

    let list = []
    if (tabsValue.value == 'inner') cityDataList.value = treeListIn.value
    if (tabsValue.value == 'out') cityDataList.value = treeListOut.value

    cityDataList.value.forEach(item => {
        if (item.isSelect) list.push(item.id)
    })
    treeRef.value.setCheckedKeys(list)

}

// 关闭
const handleClose = () => {
    cityDataList.value = []
    selectCheckList.value = []
    treeRef.value.setCheckedKeys([])
    tabsValue.value = 'inner'
    emit('handleClose')

}



// 全选
const allCheck = () => {
    let arr = cityDataList.value.filter(item => item['isSelect'])
    if (arr.length == cityDataList.value.length) {
        // 代表已全选 应该反选
        cityDataList.value.forEach(item => {
            item['isSelect'] = false
        })
    } else {
        cityDataList.value.forEach(item => {
            item['isSelect'] = true
        })
    }
    let newList = []
    let newArr = cityDataList.value.filter(item => item['isSelect'])

    let ids = []
    newArr.forEach(item => ids.push(item.id))
    treeRef.value.setCheckedKeys(ids)
    if (tabsValue.value == 'inner') newList = selectCheckList.value.filter(item => item['oversea'] != false)
    if (tabsValue.value == 'out') newList = selectCheckList.value.filter(item => item['oversea'] != true)
    selectCheckList.value = [...newList, ...newArr]
}

// 选择城市
const selectCity = (index) => {
    let ids = []
    let newList = []
    let list = []
    cityDataList.value[index]['isSelect'] = !cityDataList.value[index]['isSelect']
    cityDataList.value.forEach(item => {
        if (item.isSelect) {
            ids.push(item.id)
            list.push(item)
        }
    })
    if (tabsValue.value == 'inner') newList = selectCheckList.value.filter(item => item['oversea'] != false)
    if (tabsValue.value == 'out') newList = selectCheckList.value.filter(item => item['oversea'] != true)
    selectCheckList.value = [...newList, ...list]
    treeRef.value.setCheckedKeys(ids)
}

const selectSCityType = (index) => {
    let list = []

    cityTypeList.value[index]['isSelect'] = !cityTypeList.value[index]['isSelect']
    cityTypeList.value.forEach(item => {
        if (item.isSelect) list.push(item)
    })
    list.forEach(item => {
        item['areaName'] = item['categoryName']
    })
    selectCheckList.value = [...treeListIn.value, ...treeListOut.value, ...list]
}
const removeTab = (index, item) => {

    selectCheckList.value.splice(index, 1)  // 删除已选

    if (item.oversea != 'type') {
        // 去掉海外 国内 勾选
        let indexRow = cityDataList.value.findIndex(row => row.id == item.id)
        if (indexRow > -1) cityDataList.value[indexRow]['isSelect'] = false

        let ids = []
        cityDataList.value.forEach(item => {
            if (item['isSelect']) ids.push(item.id)
        })
        treeRef.value.setCheckedKeys(ids)
    }


    if (item.oversea == true) {
        // 海外
        let outIndex = treeListOut.value.findIndex(itemX => itemX.areaName == item.areaName)
        if (outIndex > -1) treeListOut.value[outIndex]['isSelect'] = false
    }
    if (item.oversea == false) {
        // 国内
        let inndexInner = treeListIn.value.findIndex(itemX => itemX.areaName == item.areaName)
        if (inndexInner > -1) treeListIn.value[inndexInner]['isSelect'] = false
    }
    if (item.oversea == 'type') {
        // 城市类型
        let typeIndex = cityTypeList.value.findIndex(itemX => itemX.categoryName == item.areaName)
        if (typeIndex > -1) cityTypeList.value[typeIndex]['isSelect'] = false
    }

}

// 选择节点
const currentChange = (node, nodeObj) => {

    let list = []
    treeRef.value.getCheckedNodes().forEach(item => {
        item['isSelect'] = true
        if (item.areaType == 'city' || item.areaType == null) list.push(item)
    })
    let newList = []

    if (tabsValue.value == 'inner') {
        newList = selectCheckList.value.filter(item => item['oversea'] != false)
        treeListIn.value = list
    }
    if (tabsValue.value == 'out') {
        newList = selectCheckList.value.filter(item => item['oversea'] != true)
        treeListOut.value = list
    }

    cityDataList.value = list
    selectCheckList.value = [...newList, ...list]


}

// 搜索
const searchSubject = (val) => {

    if (val == '') {
        cityDataList.value = subjectOldDataList.value
    } else {

        cityDataList.value = subjectOldDataList.value.filter(item => item.label.includes(val))
    }

}

const submit = () => {

   // if (selectCheckList.value.length == 0) return ElMessage.error('请选择城市、类型')

    let citiesList = [...treeListIn.value, ...treeListOut.value]
    let cities = [], cityTypes = [];
    let areaText = ''

    citiesList.forEach(item => {
        if (item.isSelect) {
            cities.push({ code: item.areaCode, name: item.areaName })
            areaText += item.areaName + '、'
        }
    })

    cityTypeList.value.forEach(item => {
        if (item.isSelect) {
            cityTypes.push({ code: item.categoryCode, name: item.categoryName, id: item.id })
            areaText += item.categoryName + '、'
        }
    })

    let obj = {
        cities,
        cityTypes,
        areaText,
        selectCheckList: selectCheckList.value,
        treeListOut: treeListOut.value,
        treeListIn: treeListIn.value
    }
    handleClose()
    emit('on-update', [obj, areaText])
}


</script>
<style lang="scss">
:deep .el-form-item--default .el-form-item__label {
    line-height: 27px;
}
</style>
<style lang="scss" scoped>
.search-input {
    padding: 10px 0;
}

.tabs,
.head {
    display: flex;
    height: 40px;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    width: 100%;
    border-right: 1px solid #dcdfe6;

    p {
        margin: 0;
        font-size: 14px;
        margin: 0 14px;
        cursor: pointer;

        &.active {
            color: #0049ad;
            border-bottom: 1px solid #0049ad;
        }
    }
}

.head {
    border-right: 0;

    p {
        &:nth-child(1) {
            padding-left: 10px;
            flex: 1;
            color: #0049ad;
        }

        &:nth-child(2) {
            text-align: right;
        }
    }
}

.city-box {
    padding-left: 10px;
    border-right: 1px solid #dcdfe6;
    padding-right: 10px;
}

.filter-tree {
    height: 340px;
    overflow-y: auto;
    padding-bottom: 20px;
}

.selec-city {
    padding: 10px 0;
    height: 400px;
    overflow-y: auto;
    padding-bottom: 20px;
}

.subject-con {
    .subject-list {
        margin: 0;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5ff;
        padding: 0 10px;

        &:hover {
            background: #dcdfe6;
        }

        p {
            font-size: 14px;
            flex: 1;
            margin: 5px 0;
        }

        .check-box {
            img {
                width: 15px;
                height: 15px;
                margin-left: 15px;
                cursor: pointer;
            }
        }
    }
}

.tags {
    margin-right: 10px;
    margin-bottom: 10px;
}
</style>
